package net.shopxx.action.admin;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.jsp.PageContext;

import net.sf.json.JSONArray;
import net.shopxx.bean.Pager;
import net.shopxx.entity.Brand;
import net.shopxx.entity.Groupbuy;
import net.shopxx.entity.Product;
import net.shopxx.entity.ProductCategory;
import net.shopxx.service.AreaService;
import net.shopxx.service.BrandService;
import net.shopxx.service.GroupbuyService;
import net.shopxx.service.ProductCategoryService;
import net.shopxx.service.ProductService;
import net.shopxx.util.SystemConfigUtil;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;

import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.util.StringUtil;
import com.opensymphony.oscache.web.ServletCacheAdministrator;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

/**
 * 后台Action类 - 商品团购
 */

@ParentPackage("admin")
public class GroupbuyAction extends BaseAdminAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8982038175671094442L;


	private Groupbuy groupbuy;
	@Resource
	private GroupbuyService groupbuyService;
	@Resource
	private ProductCategoryService productCategoryService;
	@Resource
	private BrandService brandService;
	@Resource
	private ProductService productService;
	@Resource
	private AreaService areaService;
	
	private String sproductCategory;
	private String sbrand;
	private String skeyword;
	// 列表
	@SuppressWarnings("unchecked")
	public String searchProduct() {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Product.class);
		if(!StringUtil.isEmpty(sproductCategory)) 
		detachedCriteria.add(Restrictions.eq("productCategory.id", sproductCategory));
		if(!StringUtil.isEmpty(sbrand))
		detachedCriteria.add(Restrictions.eq("brand.id", sbrand));
		if(pager == null)pager = new Pager();
		if(!StringUtil.isEmpty(skeyword)){
			pager.setProperty("name");
			pager.setKeyword(skeyword);
		}
		
		pager.setPageSize(Integer.MAX_VALUE);
		pager = productService.findByPager(pager,detachedCriteria);
		List<Product> ls = pager.getList();
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		for (Product product : ls) {
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			jsonMap.put("id", product.getId());
			jsonMap.put("name", product.getName());
			mapList.add(jsonMap);
		}
		
		
		JSONArray jsonArray = JSONArray.fromObject(mapList);
		return ajax(jsonArray.toString(), "text/html"); 
	}

	// 列表
	public String list() {
		pager = groupbuyService.findByPager(pager); 
		return LIST;
	}
	// 添加
	public String add() {
		return INPUT;
	}

	// 编辑
	public String edit() {
		groupbuy = groupbuyService.load(id); 
		return INPUT;
	}
	
	// 保存
    @Validations(
        
        requiredFields = {
            @RequiredFieldValidator(fieldName = "groupbuy.product.id", message = "产品不允许为空！"),
            @RequiredFieldValidator(fieldName = "groupbuy.name", message = "名称不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.desc", message = "描述不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.startTime", message = "开始时间不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.endTime", message = "结束时间不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.price", message = "价格不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.buycount", message = "最大数量不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.state", message = "团购状态不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.type", message = "团购类型不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.category", message = "团购类别不允许为空!")
        }
    )
    @InputConfig(resultName = "error")
    public String save() throws Exception {
        if (SystemConfigUtil.compareTo(groupbuy.getPrice(),new Double("0")) < 0) {
            addActionError("销售价不允许小于0");
            return ERROR;
        }
       Product product = productService.load(groupbuy.getProduct().getId());
       groupbuy.setFlagshipStore(product.getFlagshipStore());
       groupbuy.setArea(areaService.getAreaString(groupbuy.getAreaPath()));
       groupbuyService.save(groupbuy);
       flushCache();
       redirectionUrl = "groupbuy!list.action";
       return SUCCESS;
    }
	
	
	
	// 更新
    @Validations(
        
        requiredFields = {
            @RequiredFieldValidator(fieldName = "groupbuy.product.id", message = "产品不允许为空！"),
            @RequiredFieldValidator(fieldName = "groupbuy.name", message = "名称不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.desc", message = "描述不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.startTime", message = "开始时间不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.endTime", message = "结束时间不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.price", message = "价格不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.buycount", message = "最大数量不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.state", message = "团购状态不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.type", message = "团购类型不允许为空!"),
            @RequiredFieldValidator(fieldName = "groupbuy.category", message = "团购类别不允许为空!")
        }
    )
	@InputConfig(resultName = "error")
	public String update() throws Exception {
	    if (SystemConfigUtil.compareTo(groupbuy.getPrice(),new Double("0")) < 0) {
            addActionError("销售价不允许小于0");
            return ERROR;
        }
	    Product product = productService.load(groupbuy.getProduct().getId());
	    groupbuy.setFlagshipStore(product.getFlagshipStore());
	    groupbuy.setArea(areaService.getAreaString(groupbuy.getAreaPath()));
		Groupbuy persistent = groupbuyService.load(id); 
		BeanUtils.copyProperties(groupbuy, persistent, new String[] {"id", "createDate", "modifyDate"});
		groupbuyService.update(persistent);
		flushCache();
		redirectionUrl = "groupbuy!list.action";
		return SUCCESS;
	}
	

	// 删除
	public String delete() throws Exception {
		groupbuyService.delete(ids);
		flushCache();
		return ajaxJsonSuccessMessage("删除成功！");
	}
	
	// 获取商品分类树
	public List<ProductCategory> getProductCategoryTreeList() {
		return productCategoryService.getProductCategoryTreeList();
	}
	// 获取所有品牌
	public List<Brand> getAllBrand() {
		return brandService.getAll();
	}
	
	
	public Groupbuy getGroupbuy() {
		return groupbuy;
	}
	public void setGroupbuy(Groupbuy groupbuy) {
		this.groupbuy = groupbuy;
	}
	
	
	public String getSproductCategory() {
		return sproductCategory;
	}

	public void setSproductCategory(String sproductCategory) {
		this.sproductCategory = sproductCategory;
	}

	public String getSbrand() {
		return sbrand;
	}

	public void setSbrand(String sbrand) {
		this.sbrand = sbrand;
	}

	public String getSkeyword() {
		return skeyword;
	}

	public void setSkeyword(String skeyword) {
		this.skeyword = skeyword;
	}

	// 更新页面缓存
	private void flushCache() {
		Cache cache = ServletCacheAdministrator.getInstance(getRequest().getSession().getServletContext()).getCache(getRequest(), PageContext.APPLICATION_SCOPE); 
		cache.flushAll(new Date());
	}
	

}